package util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Utilities
{
	public static String getDateTime() 
	{
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        return dateFormat.format(date);
    }
	
	public static void serialize(Object object, String fileName)
	{
		try
		{
			FileOutputStream fileOut = new FileOutputStream(fileName);
			ObjectOutputStream out = new ObjectOutputStream(fileOut);
			out.writeObject(object);
			out.close();
			fileOut.close();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public static Object deserialize(String fileName)
	{
		try
		{
			FileInputStream fileIn = new FileInputStream(fileName);
			ObjectInputStream in = new ObjectInputStream(fileIn);
			Object object = in.readObject();
			in.close();
			fileIn.close();
			
			return object;
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		catch(ClassNotFoundException e)
		{
			System.out.println("Class not found");
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static <T> String convertObjectToXml(Class<T> clazz, T instance) 
	{
		try 
		{
			JAXBContext jc = JAXBContext.newInstance(clazz);
			Marshaller m = jc.createMarshaller();
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			StringWriter sw = new StringWriter();
			m.marshal(instance, sw);
			return sw.toString();
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			return null;
		}
	}
	
	public static <T> T convertXmlToObject(Class<T> clazz, String xml)
	{
		try 
		{
			JAXBContext jc = JAXBContext.newInstance(clazz);
			Unmarshaller m = jc.createUnmarshaller();
			StringReader sr = new StringReader(xml);
			@SuppressWarnings("unchecked")
			T instance = (T) m.unmarshal(sr);
			return instance;
		} 
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
}
